import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { Upload, Button, Modal, message, Popconfirm, Space } from 'antd';
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import FileOpen from '@/components/FileIframOpen';
import { flushSync } from 'react-dom';

export interface FileUploadProps {
  value?: any[];
  onChange?: any;
  onLoading?: any;
  max?: number;
  type?: string;
  readOnly?: boolean;
  multiple?: boolean;
  directory?: boolean;
  showClear?: boolean;
  cleardis?: boolean;
  ossEnum?: string;
  href?: string;
  hrefText?: string;
  hrefTaget?: string;
  actionUrl?: string;
  showUploadList?: boolean;
  text?: string;
  disabled?: boolean;
}

interface CRef {
  clear: () => void;
}

let prePropsValue: any = [];

const fileType = ['jpg', 'png', 'jpeg', 'gif', 'pdf', 'doc', 'docx'];
const imgeType = 'image/*';
const docType = '.pdf, .doc, .docx, .xml';
const FileUpload = forwardRef<CRef, FileUploadProps>((props, ref) => {
  // const postFileList = props.fileList || [];
  const [postFileList, setPostFileList] = useState<any[]>(props.value || []);
  const [fileList, setFileList] = useState<any[]>([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const { ossEnum, actionUrl, showUploadList, text } = props;
  const [showFile, setShowFile] = useState<boolean>(false);

  useEffect(() => {
    console.log(props.value,'props.value');
    
    setPostFileList(() => {
      return props.value || [];
    });
    setFileList(() => {
      return props.value || [];
    });
    // console.log(props.value, 'props.value');

  }, []);

  const propPostChange = (pFs: any) => {
    const { onChange } = props;
    if (onChange) {
      // console.log(pFs, 'pFs');

      onChange(pFs);
    }
  };
  const onChange: any = ({ fileList: newFileList = [], file }: any) => {
    // console.log(file, 'file');
    // const { onLoading } = props;
    // if (file.status == 'uploading') {
    //   if (onLoading) {
    //     onLoading(true);
    //   }
    // } else {
    //   if (onLoading) {
    //     onLoading(false);
    //   }
    // }
    //如果没有status，认为被beforeUpload拦截
    if (!file.status) {
      return;
    }
    if (file.status == 'done') {
      const response = file.response;
      if (response && response.success) {
        setPostFileList((files) => {
          files.push(Object.assign({ ...file, fileId: response.data.fileId }, response.data, { type: [] }));
          return files;
        });
        // postFileList.push(Object.assign({ ...file }, response.data, { type: [] }));
        propPostChange(postFileList);
      } else {
        file.status = 'error';
        file.name = response.errMsg || '上传失败';
        message.error(response.errMsg || '系统超时，请刷新重试！');
      }
    }
    // let arr = JSON.parse(JSON.stringify(newFileList))
    flushSync(() => {
      newFileList.splice(newFileList.length)
      setFileList(newFileList)
    // console.log(fileList, '22');

    })

    // setFileList(arr);

  };

  const clear = () => {
    setFileList([]);
    setPostFileList([]);
    propPostChange([]);
  };

  //用useImperativeHandle暴露一些外部ref能访问的属性
  useImperativeHandle(ref, () => ({
    clear,
  }));

  const onRemove = (file: any) => {
    let index = -1,
      statuIndex = -1;
    const newFileList = fileList.concat();
    let fileId = file.fileId || file.response.data.fileId
    // console.log(fileId, 'fileId');

    postFileList.map((el: any, i: number) => {
      if (el.fileId == fileId) {
        index = i;
      }
    });
    newFileList.map((el: any, i: number) => {
      if (el.fileId == fileId) {
        statuIndex = i;
        el.status = 'remove';
      }
    });
    if (index > -1) {
      setPostFileList((fs) => {
        fs.splice(index, 1);
        return fs;
      });
      // postFileList.splice(index, 1);
      // console.log(postFileList, 'postFileList11');

      propPostChange(postFileList);
    }
    if (statuIndex > -1) {
      newFileList.splice(index, 1);
      setFileList(newFileList);
    }
  };

  const handleCancel = () => {
    setPreviewVisible(false);
  };

  const getBase64 = (file: any) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  };

  const beforeUpload = (file: any) => {
    // 无法控制显示名称，在onChange中控制
    const isLt12M = file.size / 1024 / 1024 <= 500;
    if (!isLt12M) {
      // file['name'] = '文件大小不能超过 12MB!';
      file.status = 'error';
      message.error('文件大小不能超过 500MB!');
    }
    return isLt12M;
  };

  const handlePreview = async (file: any) => {
    if (file.url) {
      if (file.name) {
        const fix = file.name.substring(file.name.lastIndexOf('.') + 1);
        if (fileType.indexOf(fix) >= 0) {
          window.open(file.url);
          return;
        }
      } else {
        window.open(file.url);
        return;
      }
    }

    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewVisible(true);
    setPreviewImage(file.url || file.preview);
  };

  const isAssetTypeAnPDF = (ext: string) => {
    return /\.(pdf|PDF)(\?.*)?$/.test(ext);
  };

  const downloadPDF = (url: any) => {
    const x = new XMLHttpRequest();
    x.open('GET', url, true);
    x.responseType = 'blob';
    x.onload = function () {
      const link = window.URL.createObjectURL(x.response);
      const a = document.createElement('a');
      a.href = link;
      a.download = props.hrefText || '';
      a.click();
    };
    x.send();
  };

  return (
    <div style={{ position: 'relative' }}>
      <Space direction="vertical">
        {fileList.length > 0 && props.showClear && (
          <Popconfirm placement="rightBottom" title="确认全部删除吗？" onConfirm={clear}>
            <Button
              danger
              disabled={fileList.length <= 0 || props.cleardis}
              icon={<DeleteOutlined />}
            >
              一键清空
            </Button>
          </Popconfirm>
        )}
        <Upload
          action={actionUrl || '/api/upload/resource'}
          listType="picture"
          accept={props.type || ''}
          fileList={fileList}
          multiple={props.multiple || true}
          directory={props.directory || false}
          disabled={props.readOnly}
          onPreview={handlePreview}
          beforeUpload={beforeUpload}
          onChange={onChange}
          onRemove={onRemove}
          maxCount={props.max}
          data={{
            ossEnum,
          }}
          showUploadList={typeof showUploadList == 'boolean' ? showUploadList : true}
        >
          {fileList.length < (props.max || 5) && !props.readOnly && (
            <Button icon={<UploadOutlined />}>{text || '点击上传'}</Button>
          )}
        </Upload>
      </Space>
      {props.href && (
        <>
          {props.hrefTaget == 'open' ? (
            <a
              style={{ position: 'absolute', top: '5px', left: '130px' }}
              onClick={() => {
                setShowFile(true);
              }}
            >
              {props.hrefText || ''}
            </a>
          ) : (
            <a
              style={{ position: 'absolute', top: '5px', left: '130px' }}
              href={props.href}
              target={props.hrefTaget}
              download
            >
              {props.hrefText || ''}
            </a>
          )}
        </>
      )}
      {showFile && (
        <FileOpen
          title={props.hrefText || ''}
          fielUrl={props.href || ''}
          download={2}
          modalVisible={showFile}
          onCancel={() => {
            setShowFile(false);
          }}
        />
      )}
      {/* <Modal
                visible={previewVisible}
                title={null}
                footer={null}
                onCancel={() => handleCancel()}
            >
                {previewImage && <a alt="example" style={{ width: '100%' }} src={previewImage} />}
            </Modal> */}
    </div>
  );
});
export default FileUpload;
